<!--
 * @Description: 组织人员-添加组织人员
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2024-05-08
-->
<template>
  <div class="add">
    <a-modal v-model:visible="visible" title="添加人员" @ok="onOk">
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="绑定账号" v-bind="validateInfos.userPhone">
          <a-input-search type="number" v-model:value="form.state.userPhone" placeholder="请输入" @search="form.onUserPhoneSearch" />
          <div v-if="form.searchSuccess">
            {{ form.state.userPhone }}
            <check-circle-outlined :style="{ color: SUCCESS_COLOR }" />
          </div>
        </a-form-item>
        <a-form-item label="姓名" v-bind="validateInfos.userName">
          <a-input v-model:value="form.state.userName" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="所在组织" v-bind="validateInfos.depts">
          <a-tree-select v-model:value="form.state.depts" :tree-data="deptOptions" allow-clear tree-checkable :show-checked-strategy="TreeSelect.SHOW_PARENT" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="所属角色" v-bind="validateInfos.roles">
          <a-select v-model:value="form.state.roles" :options="roleOptions" placeholder="请选择" mode="tags" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { CheckCircleOutlined } from '@ant-design/icons-vue'
  import type { SelectProps } from 'ant-design-vue'
  import { Form, message, TreeSelect } from 'ant-design-vue'
  import { computed, reactive, ref, watch } from 'vue'

  import { requestGetCompanyRoleList } from '/@/api/business/company/config'
  import { requestSaveDeptUser } from '/@/api/business/company/dept'
  import { IdentityTypeEnum } from '/@/api/business/company/dept/enum'
  import { requestCheckAccount } from '/@/api/system/ysys-user/account'
  import { SUCCESS_COLOR } from '/@/design/thems'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getCompanyInfo } from '/@/storage'
  import { convertSecondOptions } from '/@/utils/org'

  const { companyId } = getCompanyInfo()

  const props = defineProps({
    visible: { type: Boolean, default: false },
    depts: { type: Array, default: () => [] },
  })

  const emits = defineEmits(['update:visible', 'success'])

  const visible = computed({
    get: () => props.visible,
    set: (val: boolean) => emits('update:visible', val),
  })

  watch(
    () => visible.value,
    (newVal, oldVal) => {
      if (newVal && !oldVal) {
        resetFields()
        initRoles()
      }
    },
  )

  /** 所在组织-选项 */
  const deptOptions = computed(() => convertSecondOptions(props.depts))

  /** 角色-选项 */
  const roleOptions = ref<SelectProps['options']>([])

  /**
   * 初始化角色
   */
  const initRoles = async () => {
    const { responseData } = await requestGetCompanyRoleList({ companyId })
    roleOptions.value = responseData.map((item) => ({ label: item.roleName, value: item.roleId }))
  }

  /** 表单配置 */
  const form = reactive({
    state: {
      userPhone: '',
      userName: '',
      depts: [] as number[],
      roles: [] as number[],
    },
    rule: {
      userPhone: [
        { required: true, message: '请输入账号' },
        {
          validator: async (_, val) => {
            if (!val) return Promise.resolve()
            const { responseCode } = await requestCheckAccount({ account: val })
            if (responseCode === HttpCodeEnum.SUCCESS) {
              form.searchSuccess = true
              return Promise.resolve()
            }
            form.searchSuccess = false
            return Promise.reject()
          },
          message: '搜索不到用户，请输入正确的数字资产银行账号。',
          trigger: 'blur',
        },
      ],
      userName: [{ required: true, message: '请输入姓名' }],
      depts: [{ required: true, message: '请输入组织' }],
      roles: [{ required: true, message: '请选择角色' }],
    },
    searchSuccess: false,
    onUserPhoneSearch: () => validate('userPhone'),
  })
  /** 表单hook */
  const { validate, validateInfos, resetFields } = Form.useForm(form.state, form.rule)

  /** 监听账号改变，清空账号校验结果 */
  watch(
    () => form.state.userPhone,
    () => (form.searchSuccess = false),
  )

  /**
   * 确定
   */
  const onOk = () => {
    validate()
      .then(async () => {
        const { userName, userPhone, depts, roles } = form.state
        const { responseCode } = await requestSaveDeptUser({
          companyId,
          identityType: IdentityTypeEnum.PHONE,
          userName: userName,
          loginName: userPhone,
          deptIds: depts,
          roleIds: roles,
        })
        if (responseCode === HttpCodeEnum.SUCCESS) {
          message.success('添加成功')
          visible.value = false
          emits('success')
        }
      })
      .catch(() => {})
  }
</script>

<style lang="less" scoped></style>
